package com.example.petstore_2.controller;

import com.example.petstore_2.common.CommonResponse;
import com.example.petstore_2.domain.MessageLog;
import com.example.petstore_2.domain.User;
import com.example.petstore_2.service.MessageService;
import com.example.petstore_2.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
public class ChatController {
    @Autowired
    private MessageService messageService;

    /**
     * 获取全部消息
     * @param token
     * @return
     */
    @GetMapping("/messages")
    public CommonResponse userGetMessage(@RequestHeader("Authorization") String token){
        String username = JWTUtil.getTokenInfo(token, "username");
        return messageService.getMessagesByUser(username);
    }

    /**
     * 关闭的时候调用，储存离开时间
     * @param token
     * @return
     */
    @PostMapping("/closeChat")
    public CommonResponse userCloseChat(@RequestHeader("Authorization") String token) {
        String username = JWTUtil.getTokenInfo(token, "username");
        MessageLog messageLog = new MessageLog();
        messageLog.setUserLeftTime(LocalDateTime.now());
        messageLog.setUsername(username);
        return messageService.updateMessageLogForUser(username, messageLog);
    }
}
